import React, { useState } from 'react';

type PlantDetails = {
  family?: string;
  general?: string;
  species?: string;
  info?: string;
  area?: string;
  pharmacology?: string;
  climate?: string;
  soil_type?: string;
  water_requirements?: string;
  growth_cycle?: string;
  history?: string;
  cultural_significance?: string;
  cultivation_suggest?: string;
};

type PlantResponse = {
  name: string;
  details: PlantDetails;
};

export const PlantIdentify: React.FC = () => {
  const [imgUrl, setImgUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<PlantResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);

  const onFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    setError(null);
    try {
      const form = new FormData();
      form.append('file', file);
      const res = await fetch('/api/upload_image', { method: 'POST', body: form });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || '上传失败');
      setImgUrl(json.url);
    } catch (err: any) {
      setError(err.message || '上传失败');
    } finally {
      setUploading(false);
    }
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setData(null);
    try {
      const res = await fetch('/api/get_plant_response', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ img_url: imgUrl }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || '请求失败');
      setData(json as PlantResponse);
    } catch (err: any) {
      setError(err.message || '未知错误');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="card">
      <h2>植物识别</h2>
      <form onSubmit={onSubmit} className="form">
        <input
          type="url"
          placeholder="粘贴图片 URL（需公网可访问）"
          value={imgUrl}
          onChange={(e) => setImgUrl(e.target.value)}
        />
        <input type="file" accept="image/*" onChange={onFileChange} />
        <button type="submit" disabled={!imgUrl || loading}>
          {loading ? '识别中...' : uploading ? '上传中...' : '提交'}
        </button>
      </form>

      {error && <div className="error">{error}</div>}

      {data && (
        <div className="result">
          <div className="result-header">
            <span className="tag">植物</span>
            <h3>{data.name}</h3>
          </div>
          <div className="kv-grid">
            {Object.entries(data.details || {}).map(([k, v]) => (
              v ? (
                <div className="kv" key={k}>
                  <div className="k">{k}</div>
                  <div className="v">{v}</div>
                </div>
              ) : null
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

